import {
  HttpException,
  HttpStatus,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { CreateNewDto } from '../dto/new/create-new.dto';
import { UpdateNewDto } from '../dto/new/update-new.dto';
import { New } from '../entities/new.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ResMsg } from 'src/utils/public.enum';
import { ListNewDto } from '../dto/new/list-new.dto';
import { GoodsService } from './goods.service';

@Injectable()
export class NewService {
  constructor(
    @InjectRepository(New, 'shop')
    private readonly newRepository: Repository<New>,
    private readonly goodsService: GoodsService,
  ) {}

  async create(createNewDto: CreateNewDto) {
    const isExitGoods = await this.findOneByGoodsIs(+createNewDto.goodsId);
    if (isExitGoods) {
      // return '当前商品已存在'
      throw new HttpException(
        {
          status: HttpStatus.BAD_REQUEST,
          error: '当前商品已存在',
        },
        HttpStatus.BAD_REQUEST,
      );
    }
    const row = new New(createNewDto);
    const result = await this.newRepository.save(row);

    const goodsDBRow = await this.goodsService.findOne(+createNewDto.goodsId);
    const goodsNew = await this.goodsService.update(+createNewDto.goodsId, {
      ...goodsDBRow,
      isHot: 1,
    });

    if (result && goodsNew === ResMsg.Success) {
      return ResMsg.Success;
    }

    if (result) {
      return ResMsg.Success;
    }
    return ResMsg.Fail;
  }

  async findAll(listNewDto: ListNewDto) {
    try {
      const {
        id = null,
        title = '',
        desc = '',
        categoryId = null,
        goodsId = null,
      } = listNewDto.queryDto;
      const queryBuilder = this.newRepository.createQueryBuilder('new');

      if (id) {
        queryBuilder.where('new.id = :id', { id });
      }

      if (goodsId) {
        queryBuilder.andWhere('new.goods_id = :goodsId', { goodsId });
      }

      if (categoryId) {
        queryBuilder.andWhere('new.category_id = :categoryId', { categoryId });
      }

      queryBuilder
        .andWhere('new.is_delete = :isDelete', { isDelete: 1 })
        .andWhere('new.title LIKE :title AND new.desc LIKE :desc', {
          title: `%${title}%`,
          desc: `%${desc}%`,
        });

      const [list, total] = await queryBuilder
        .orderBy('new.modify_time', 'DESC')
        .skip((listNewDto.pageDto.pageNo - 1) * listNewDto.pageDto.pageSize)
        .take(listNewDto.pageDto.pageSize)
        .getManyAndCount();

      return {
        list,
        total,
        ...listNewDto.pageDto,
      };
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findOne(id: number) {
    try {
      const res = await this.newRepository.findOneBy({
        id,
        isDelete: 1,
      });
      return res;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async update(id: number, updateNewDto: UpdateNewDto) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          ...updateNewDto,
        };
        const result = this.newRepository.save(data);
        if (result) {
          return ResMsg.Success;
        }
        return ResMsg.Fail;
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async remove(id: number) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          isDelete: -1,
        };
        const result = this.newRepository.save(data);
        if (result) {
          return ResMsg.Success;
        }
        return ResMsg.Fail;
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findOneByGoodsIs(goodsId: number) {
    try {
      const res = await this.newRepository.findOneBy({
        goodsId,
        isDelete: 1,
      });
      return res;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
